package com.bilibili.server.service;

import com.bilibili.server.entity.Category;
import com.bilibili.server.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CategoryService {
    @Autowired
    private CategoryRepository categoryRepository;

    // 获取所有启用的分类
    public List<Category> getAllActiveCategories() {
        return categoryRepository.findByStatus(1);
    }

    // 获取单个分类详情
    public Category getCategoryById(int categoryId) {
        Optional<Category> categoryOptional = categoryRepository.findById(categoryId);
        return categoryOptional.orElse(null);
    }

    // 管理员获取所有分类（包括未启用的）
    public List<Category> getAllCategories() {
        return categoryRepository.findAll();
    }

    // 创建新分类
    public Category createCategory(Category category) {
        // 检查分类名称是否已存在
        Optional<Category> existingCategory = categoryRepository.findByName(category.getName());
        if (existingCategory.isPresent()) {
            throw new RuntimeException("分类名称已存在");
        }
        return categoryRepository.save(category);
    }

    // 更新分类
    public Category updateCategory(int categoryId, Category category) {
        Optional<Category> categoryOptional = categoryRepository.findById(categoryId);
        if (categoryOptional.isPresent()) {
            Category existingCategory = categoryOptional.get();
            // 更新分类信息
            existingCategory.setName(category.getName());
            existingCategory.setDescription(category.getDescription());
            existingCategory.setStatus(category.getStatus());
            existingCategory.setParent(category.getParent());
            return categoryRepository.save(existingCategory);
        }
        return null;
    }

    // 删除分类
    public void deleteCategory(int categoryId) {
        categoryRepository.deleteById(categoryId);
    }
}